package com.qilu.careprogram.controller;

import com.qilu.careprogram.common.AjaxResult;
import com.qilu.careprogram.service.SmartQaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/smartqa")
public class SmartQaController {

    @Autowired
    private SmartQaService smartQaService;

    @PostMapping("/createSession")
    public AjaxResult createSession() {
        try {
            String sessionId = smartQaService.createSession();
            return AjaxResult.success().put("sessionId", sessionId);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    @PostMapping(value = "/chat", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public void chatStream(@RequestBody Map<String, String> request, HttpServletResponse response) throws Exception {
        try {
            String sessionId = request.get("sessionId");
            String question = request.get("question");
            String hospitalNumber = request.get("hospitalNumber");
            System.out.println(hospitalNumber);

            // 设置响应头
            response.setContentType("text/event-stream");
            response.setCharacterEncoding("UTF-8");
            response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache");
            response.setHeader(HttpHeaders.CONNECTION, "keep-alive");

            // 调用流式服务
            smartQaService.chatStream(sessionId, question, hospitalNumber, response.getOutputStream());
        } catch (Exception e) {
            response.getWriter().write("data: {\"error\":\"" + e.getMessage() + "\"}\n\n");
            response.flushBuffer();
        }
    }

    @PostMapping("/deleteSession")
    public AjaxResult deleteSession(@RequestBody Map<String, String> request) {
        try {
            smartQaService.deleteSession(request.get("sessionId"));
            return AjaxResult.success();
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }
}